<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\monthsmodel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;

class monthscontroller extends Controller
{
    public function add(Request $request){
        $name = $request['name'];
        $pwd = $request['pwd'];
        $sex = $request['sex'];
        $age = $request['age'];
        $tel = $request['tel'];
        $file = $request->file("img");
//        dd($file);
        //验证
        $validate = Validator::make($request->all(),
            [
            $name => 'required',
            $pwd => 'string',
                $file=>'max:1024*3'
    ]
       , [
            "$file.max"=>"图片的大小不能大于3M"
        ]
);
        if($validate->fails())
        {
            return $validate->errors()->first();
        }

        //new orm
        $fsp = new monthsmodel();
        $fsp['name']=$name;
        $fsp['sex']=$sex;
        $fsp['age']=$age;
        $fsp['tel']=$tel;
        $fsp['pwd']=$pwd;
        $fsp->save();
        $id = $fsp->id;

        //设置图片上传类型
        $type = ['jpg','jpeg','png'];
        if (!in_array($file->getClientOriginalExtension(),$type)){
            dd("只能上传'jpg','jpeg','png'类型的图片");
        }
        //设置图片路径
        $path = __DIR__."/../../../public/imgss".intval($id/1000);
        $a = $file->getClientOriginalExtension();
        $filename = $id.".".$a;
        $file->move($path,$filename);
        $img = $path.'/'.$filename;
        $fsp['img']=$img;
        $a = $fsp->save();
        if ($a){
            return"<script>alert('添加成功');location.href='shows'</script>";
        }else{
            return"<script>alert('添加失败');location.href='monthadds'</script>";
        }



    }
    public function shows(){
        $data = monthsmodel::li();
        return view("monthlists",['data'=>$data]);
    }

    public function get(Request $request){
        $id = $request['id'];
        $fsp = monthsmodel::find($id);
        $img = $fsp['img'];
        return response()->file($img);
    }

    public function gets(Request $request){
        $id = $request['id'];
        $fsp = monthsmodel::find($id);
        $img = $fsp['img'];
        return response()->download($img,$id.".png");
    }
    public function del(Request $request){
        $id = $request['id'];
         $a = DB::delete('delete from users where id = ?',[$id]);
        if ($a){
            return"<script>alert('删除成功');location.href='shows'</script>";
        }else{
            return"<script>alert('删除失败');location.href='shows'</script>";
        }
    }
    //缩略图
    public function tu(){

        $img = Image :: make('./../../..8.png');
 $img-> resize(200,180);
// $img->插入（’public / watermark.png’;
// $img-> save（’public / bar.jpg’）;
        $img->save("public/imgss0");
        return response()->file($img);
    }




}

